//
//  QRCodeViewController.swift
//  weibo_swift
//
//  Created by dulinlong on 15/7/2.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewController: UIViewController,UITabBarDelegate,AVCaptureMetadataOutputObjectsDelegate {


    @IBOutlet weak var tabBar: UITabBar!
    
    @IBOutlet weak var heightConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var widthConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var topConstraint: NSLayoutConstraint!
    
    @IBOutlet weak var scanImage: UIImageView!
    
    @IBOutlet weak var resultLabel: UILabel!

    @IBAction func myCardClick(sender: AnyObject) {
        navigationController?.pushViewController(QRCodeMyCardViewController(), animated: true)

    }
    @IBAction func close(sender: AnyObject) {
        dismissViewControllerAnimated(true , completion:nil)
    }
    

    @IBAction func photographClick(sender: AnyObject) {
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        tabBar.selectedItem = tabBar.items![0]
        
        //设置二维码扫描环境
        setupSession()
        setupLayers()
    }
    
    override func viewDidAppear(animated: Bool) {
        
        startAnimation()
        //开始扫描
        startScan()

    }

    
    ///  开始扫描
    private func startScan() {
        session.startRunning()
    }
    
    private func startAnimation(){
        topConstraint.constant = -heightConstraint.constant
        view.layoutIfNeeded()
        UIView.animateWithDuration(2.0) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            
            self.topConstraint.constant = self.heightConstraint.constant
            self.view.layoutIfNeeded()
        }
        
    }
    
    //MARK - TabBar代理
   func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem){
    print(item.tag)
    
    //1.先移除动画
    print(scanImage.layer.removeAllAnimations())
    //2.调整高度
    heightConstraint.constant = widthConstraint.constant * (item.tag == 10 ? 1 : 0.5)
    startAnimation()
    }
    
    ///  设置会话
    func setupSession(){
        // 1. 判断是否能够添加设备
        if !session.canAddInput(inputDevice) {
            print("无法添加输入设备")
            return
        }
        
        // 2. 判断能否添加输出数据
        if !session.canAddOutput(outputData) {
            print("无法添加输出数据")
            return
        }
        
        // 3. 添加设备
        session.addInput(inputDevice)
        session.addOutput(outputData)
//        print(outputData.availableMetadataObjectTypes)
        
        // 4. 设置扫描数据类型,检测所有的数据类型
        outputData.metadataObjectTypes = outputData.availableMetadataObjectTypes
        // 5. 设置输出代理
        outputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    }
    
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        //清空图层
        clearDrawlayer()
        
        for object in metadataObjects {
            //判断识别对象类型
            if object is AVMetadataMachineReadableCodeObject{
                //转换数据类型
            let dataObject = previewLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
            
            drawCornerShap(dataObject)
            resultLabel.text = dataObject.stringValue
            }}
    }
    
    //清空图层
    func clearDrawlayer(){
        if drawLayer.sublayers == nil{
            return
        }
        
        for sublayer in drawLayer.sublayers!{
            sublayer.removeFromSuperlayer()
        }
    }
    
    /// 设置图层
    func setupLayers() {
        
        //插入绘制图层
        drawLayer.frame = view.bounds
        view.layer.insertSublayer(drawLayer, atIndex: 0)
        //
        previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        previewLayer.frame = view.bounds
        view.layer.insertSublayer(previewLayer, atIndex: 0)
    }
    
    //绘制线条
    func drawCornerShap(dataObject: AVMetadataMachineReadableCodeObject){
        
        if dataObject.corners.isEmpty {
            return
        }
        
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        layer.path = cornersPath(dataObject.corners)
        
        // 添加到绘图图层
        drawLayer.addSublayer(layer)
    }
    
    func cornersPath(corners: NSArray) -> CGPathRef{
        let path = UIBezierPath()
        var point = CGPoint()
        
        print(corners)
        // 1. 移动到第一个点
        var index = 0
        CGPointMakeWithDictionaryRepresentation((corners[index++] as! CFDictionaryRef), &point)
        path.moveToPoint(point)
        
        // 2. 遍历剩余的点
        while index < corners.count {
            CGPointMakeWithDictionaryRepresentation((corners[index++] as! CFDictionaryRef), &point)
            path.addLineToPoint(point)
        }
        
        // 3. 关闭路径
        path.closePath()
        
        return path.CGPath
        
    }
    
    
    //绘制图层
    lazy var drawLayer:CALayer = CALayer()
    /// 预览图层
    lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        return AVCaptureVideoPreviewLayer(session: self.session)
        }()
    //session桥接
    lazy var session:AVCaptureSession = AVCaptureSession()
    
    //输入设备
    lazy var inputDevice:AVCaptureDeviceInput? = {
        //获取摄像头
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            return try AVCaptureDeviceInput(device: device)
        } catch {
            print(error)
            return nil
        }
    }()
    
    // 输出数据
    lazy var outputData: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
}
